package org.itli.jnsocket.Service.ServiceImpl;


import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.itli.jnsocket.Mapper.UserMapper;
import org.itli.jnsocket.Pojo.JnSysUser;
import org.itli.jnsocket.Service.UserService;
import org.itli.jnsocket.Util.JWTUtil;
import org.itli.jnsocket.Util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    UserMapper mapper;

    Gson gson;

    @Autowired
    public void setMapper(UserMapper mapper) {
        this.mapper = mapper;
    }

    @Autowired
    public void setGson(Gson gson) {
        this.gson = gson;
    }

    JWTUtil jwt = new JWTUtil();

    //登录逻辑
    @Override
    public String Login(String username, String password,String ip) {
        password = MD5Util.getMD5(password);
        String login;
        try{
            login = mapper.Login(username, password);
            if(login == null) {
                log.info("账号或密码错误");
                return "0";
            }
            else {
                log.info("登录成功");
                Map<String, Object> claim = new HashMap<>();
                claim.put("username",login);
                String token = jwt.genToken(claim);
                //记录登录相关信息
                mapper.LoginAddIP(username, ip);
                return token;
            }
        } catch (Exception e) {
            log.info(e.getLocalizedMessage());
            return "error";
        }
    }

    @Override
    public String Register(String username, String password) {
        password = MD5Util.getMD5(password);
        try{
            int register = mapper.Register(username, password);
            if(register == 0) {
                return "0";
            }
            else {
                return "1";
            }
        } catch (Exception e) {
            log.info(e.getLocalizedMessage());
            return "error";
        }
    }

    @Override
    public String MyInfo(String username) {
        try{
            JnSysUser jnSysUser = mapper.MyInfo(username);
            String json = gson.toJson(jnSysUser);
            return json;
        } catch (Exception e) {
            return "error";
        }
    }
}
